package com.adnaan.backend.utils;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.symmetric.AES;
import cn.hutool.crypto.symmetric.SymmetricAlgorithm;

/**
 * author: adnaan
 * create: 2025-01-06 18:02
 * Description:
 */
public class PasswordUtils {

    /**
     * 加密
     *
     * @param password 密码
     * @param salt     盐
     * @return 加密后的密码
     */
    public static String encrypt(String password, String salt) {
        // 生成密钥
        byte[] encoded = SecureUtil.generateKey(SymmetricAlgorithm.AES.getValue(), salt.getBytes()).getEncoded();
        // 返回加密
        AES aes = SecureUtil.aes(encoded);
        return aes.encryptBase64(password);
    }

    /**
     * 解密
     *
     * @param password 密码
     * @param salt     盐
     * @return 解密后的密码
     */
    public static String decrypt(String password, String salt) {
        // 生成密钥
        byte[] encoded = SecureUtil.generateKey(SymmetricAlgorithm.AES.getValue(), salt.getBytes()).getEncoded();
        // 返回解密
        AES aes = SecureUtil.aes(encoded);
        return aes.decryptStr(password);
    }

    public static void main(String[] args) {
        String salt = RandomUtil.randomString(16);
        String encrypt = encrypt("123456", salt);

        String decrypt = decrypt(encrypt, salt);
        System.out.println(encrypt);
        System.out.println(decrypt);
    }
}
